package com.lanjiu.lib.communication.netty;

import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.lib.communication.IMSConfig;
import com.lanjiu.lib.communication.interf.IMSClientInterface;
import com.lanjiu.lib.communication.util.CheckSumResult;
import com.lanjiu.lib.communication.util.JCRC32;
import com.lanjiu.lib.utils.log.Logger;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @description: 消息接收处理handler
 * @author: Panwei
 * @date: 2019/10/28 14:45
 */
public class TCPReadHandler extends SimpleChannelInboundHandler<BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage> {

    private IMSClientInterface mImsClient;
    private JCRC32 mJCRC32;

    public TCPReadHandler(IMSClientInterface imsClient) {
        this.mImsClient = imsClient;
        this.mJCRC32 = new JCRC32();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Logger.print("TCPReadHandler channelInactive() 频道不活跃");
        resetConnect(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Logger.print("TCPReadHandler exceptionCaught() 异常捕获：" + cause.getMessage());
        resetConnect(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BusinessProtocolMessageStandard.CheckUnifiedEntranceMessage msg) throws Exception {
        if (msg == null) return;
        BusinessProtocolMessageStandard.UnifiedEntranceMessage message = msg.getUnifiedEntranceMessage();
        if (message == null || message.getHead() == null || IMSConfig.HEART_PACKAGE_PHONE.equals(message.getHead().getMsgType()) || IMSConfig.REPLY_NOTICE_ACCEPT_SUCCESS.equals(message.getHead().getMsgType()))
            return;
        Logger.print("channelRead:" + msg.toString());
        mImsClient.getRequestTimeoutTimerManager().remove(msg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
        CheckSumResult checkSumResult = mJCRC32.checkSumValidateProtocol(msg, message);
        if (checkSumResult.b_result) {
            BusinessProtocolMessageStandard.UnifiedEntranceMessage entranceMessage = mImsClient.getMsgDispatcher().beforeDispatchMsg(ctx.channel(), message);
            if (entranceMessage != null) {
                BusinessProtocolMessageStandard.Head head = entranceMessage.getHead();
                if (IMSConfig.STATUS_REPORT_SUCCESS.equals(head.getStatusReport()) ||
                        IMSConfig.STATUS_REPORT_REFUSE.equals(head.getStatusReport()) ||
                        IMSConfig.STATUS_REPORT_EXCEPTION.equals(head.getStatusReport())) {
                    // 消息接收成功！从重发管理器中移除
                    mImsClient.getMsgTimeoutTimerManager().remove(msg.getUnifiedEntranceMessage().getHead().getUniqueIdentify());
                }
                mImsClient.getMsgDispatcher().receivedMsg(entranceMessage);
            } else {
                mImsClient.getMsgDispatcher().receivedMsg(generateCanceledMessage(message));
            }
        } else {
            Logger.print("消息校验失败");
            mImsClient.getMsgDispatcher().receivedMsg(checkSumResult.getMessage());
        }
    }

    private void resetConnect(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        if (channel != null) {
            channel.close();
            ctx.close();
        }
        // 触发重连
        mImsClient.resetConnect();
    }

    private BusinessProtocolMessageStandard.UnifiedEntranceMessage generateCanceledMessage(BusinessProtocolMessageStandard.UnifiedEntranceMessage msg) {
        BusinessProtocolMessageStandard.Head head = BusinessProtocolMessageStandard.Head.newBuilder(msg.getHead()).setMsgContentType(IMSConfig.MSG_CONTENT_TYPE_MESSAGE_CANCEL).build();
        return BusinessProtocolMessageStandard.UnifiedEntranceMessage.newBuilder(msg).setHead(head).build();
    }
}
